package com.want.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import com.want.domain.entity.WebConfig;
import com.want.model.dto.Result;
import com.want.model.dto.ResultUtil;
import com.want.repository.WebConfigRepository;
import com.want.resp.front.dto.WebConfigDto;
import com.want.util.MyBeanUtil;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;

/**
 * @author WangZhiJian
 * @since 2021/12/23
 */
@RestController
@RequestMapping("webConfig")
public class WebConfigController {

    @Resource
    private WebConfigRepository webConfigRepository;

    @GetMapping("/")
    public Mono<WebConfigDto> getWebConfig(){
        return webConfigRepository.selectWebConfig()
                .map(webConfig -> MyBeanUtil.copyProperties(webConfig,WebConfigDto.class));
    }

    @PostMapping("/add")
    @SaCheckRole(value = "admin")
    public Mono<Result<WebConfigDto>> addWebConfig(@RequestBody WebConfigDto webConfigDto){
        return Mono.just(webConfigDto)
                .zipWith(Mono.justOrEmpty(webConfigDto.getId())
                        .flatMap(webConfigRepository::findById)
                        .switchIfEmpty(Mono.defer(()-> Mono.just(new WebConfig())))
                )
                .map(tuple2 -> MyBeanUtil.copyPropertiesIngoreNull(WebConfig.class,tuple2.getT2(),tuple2.getT1()))
                .flatMap(webConfigRepository::save)
                .map(webConfig -> MyBeanUtil.copyProperties(webConfig,WebConfigDto.class))
                .map(ResultUtil::ofSuccess);
    }
}
